package com.sense.sensedialprehandle.utils;

import com.sense.sensedialprehandle.enums.ResultStatusCode;
import com.sense.sensedialprehandle.pojo.CommonResponse;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;

@Slf4j
public class ComResponseUtil {
    public static CommonResponse success() {
        return new CommonResponse(ResultStatusCode.Success.getCode(),ResultStatusCode.Success.getMsg());
    }

    public static CommonResponse success(String msg) {
        return new CommonResponse(ResultStatusCode.Success.getCode(),msg);
    }

    /**
     * 返回默认错误信息
     * @param request
     * @param e
     * @return
     */
    public static CommonResponse getExceptionDetail(HttpServletRequest request,Exception e){
        Map<String,Object> requestInfos = RequestUtils.getRequestInfos(request);
        if(((Map)requestInfos.get("params")).containsKey("ex")){
            requestInfos.put("exception:", Collections.singletonList(getErrorMessage(e)));
        }else{
            requestInfos.put("exception:",null);
        }
        return new CommonResponse(ResultStatusCode.Error.getCode(),ResultStatusCode.Error.getMsg(),requestInfos);
    }
    public static CommonResponse getExceptionDetails(HttpServletRequest request,Exception e){
        Map<String,Object> requestInfos = RequestUtils.getRequestInfos(request);
        requestInfos.put("exception:","\r\n"+getErrorMessage(e));
        return new CommonResponse(ResultStatusCode.Error.getCode(),ResultStatusCode.Error.getMsg(),requestInfos);
    }

    public static CommonResponse getExceptionDetail(String code,HttpServletRequest request,Exception e){
        return getExceptionDetail(request,e).setCode(code);
    }



    /**
     * 获取异常信息
     *
     * @param e 异常
     */
    public static String getErrorMessage(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            // 将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    log.info(e1.getMessage());
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }


}
